package com.ypx.ec.ware.listener;


import com.rabbitmq.client.Channel;
import com.ypx.ec.common.to.mq.OrderTo;
import com.ypx.ec.common.to.mq.StockLockedTo;
import com.ypx.ec.ware.service.WareSkuService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
@Component
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {
    @Autowired
    WareSkuService wareSkuService;
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        try {
            wareSkuService.unlockStock(to);

            //不批量处理
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){

            //将消息重新回队
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
    /**
     * 监听主动解锁库存的消息
     *
     * @param orderDTO
     */
    @RabbitHandler
    public void handleUnlock(OrderTo orderDTO, Message message, Channel channel) throws IOException {
        System.out.println("收到主动解锁库存的消息");

        try {
            wareSkuService.unlockStock(orderDTO);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
